<template>
	<view class="page">
		<u--form errorType="toast" :model="form" ref="myForm" :rules="rules" labelWidth="120">
			<u-form-item label="门店LOGO" borderBottom v-if="type==='1'">
				<div class="flex flex justify-end">
					<view>
						<u-upload
							:fileList="fileList" 
							:maxCount="1" 
							@delete="deletePic"
							@afterRead="afterRead"
						/>
					</view>
				</div>
			</u-form-item>
			<u-form-item label="门店名称" prop="storeName" borderBottom>
				<u-input v-model="form.storeName" border="none" placeholder="请输入" inputAlign="right" :disabled="type==='2'" disabledColor="#fff"/>
			</u-form-item>
			<u-form-item label="门店联系人" prop="linkMan" borderBottom>
				<u-input v-model="form.linkMan" border="none" placeholder="请输入" inputAlign="right" :disabled="type==='2'" disabledColor="#fff" />
			</u-form-item>
			<u-form-item label="默认推荐人" prop="staffName" borderBottom @click="$u.route('/pages/selectPage/lianChuang', {dty:'parent'})">
				<u-input v-model="form.staffName" border="none" placeholder="请输入" inputAlign="right" disabled disabledColor="#fff" />
				<u-icon slot="right" name="arrow-right"/>
			</u-form-item>
			<u-form-item label="联系电话" prop="mobile" borderBottom>
				<u-input v-model="form.mobile" border="none" placeholder="请输入" inputAlign="right" :disabled="type==='2'" disabledColor="#fff" />
			</u-form-item>
			<u-form-item label="营业时间" prop="openingTime" borderBottom @click="openTimePick('open')">
				<u-input v-model="form.openingTime" border="none" placeholder="请输入" inputAlign="right" disabledColor="#fff" />
				<u-icon slot="right" name="arrow-right"/>
			</u-form-item>
			<u-form-item label="打样时间" prop="closingTime" borderBottom @click="openTimePick('closing')">
				<u-input v-model="form.closingTime" border="none" placeholder="请输入" inputAlign="right" disabledColor="#fff" />
				<u-icon slot="right" name="arrow-right"/>
			</u-form-item>
			<u-form-item label="支付商户编码" prop="payAccount" borderBottom>
				<u-input v-model="form.payAccount" border="none" placeholder="请输入" inputAlign="right" :disabled="type==='2'" disabledColor="#fff" />
			</u-form-item>
			<u-form-item label="会员共享码" prop="sharingCode" borderBottom v-if="type==='1'">
				<u-input v-model="form.sharingCode" border="none" placeholder="请输入" inputAlign="right" disabledColor="#fff" />
			</u-form-item>
			<u-form-item label="门店地区" prop="areaFullName" borderBottom @click="onSeqy">
				<u-input v-model="form.areaFullName" border="none" placeholder="请选择" inputAlign="right" disabled disabledColor="#fff" />
				<u-icon slot="right" name="arrow-right"/>
			</u-form-item>
			<u-form-item label="门店详细地址" prop="address" borderBottom>
				<u-input v-model="form.address" border="none" placeholder="请输入内容" inputAlign="right" :disabled="type==='2'" disabledColor="#fff"/>
			</u-form-item>
			<u-form-item label="坐标位置" prop="coordinate" borderBottom>
				<u-input v-model="form.coordinate" border="none" placeholder="请输入内容" inputAlign="right" :disabled="type==='2'" disabledColor="#fff"/>
			</u-form-item>
			<u-row v-if="type==='1'">
				<u-col span="6">
					<u-form-item label="是否默认" prop="isDefault">
						<u-switch slot="right" v-model="form.isDefault" activeColor="#e54d42"></u-switch>
					</u-form-item>
				</u-col>
				<u-col span="6">
					<u-form-item label="是否禁用" prop="isDelete">
						<u-switch slot="right" v-model="form.isDelete" activeColor="#e54d42"></u-switch>
					</u-form-item>
				</u-col>
			</u-row>
		</u--form>
		
		<view class="pl-60 pr-60 mt-60">
			<u-button color="#e54d42" text="提交" @click="submit" size="large" v-if="type === '1'" />
			<u-button color="#e54d42" text="查看店铺二维码" @click="viewCode" size="large" v-if="type === '2'"/>
		</view>
		<u-picker 
			ref="uAreaPicker"
			:show="showArea" 
			:columns="areas" 
			keyName="name" 
			:closeOnClickOverlay="true"
			@cancel="showArea=false"
			@close="showArea=false"
			@confirm="confirmAreas" 
			@change="changeHandler">
		</u-picker>
		<u-datetime-picker
			ref="timePicker"
			:show="showTimePicker"
			v-model="time"
			mode="time"
			@cancel="showTimePicker=false"
			@close="showTimePicker=false"
			@confirm="onConfirmTime"
		></u-datetime-picker>
		<u-toast ref="uToast"></u-toast>
	</view>
</template>

<script>
	import cDate from '@/common/date.js'
	export default {
		data() {
			return {
				type: '1', // 1编辑模式 2 查看模式
				showArea:false,
				areas: [],
				percentage: 0,
				fileList: [],
				time:'',
				timeType: 'open',
				showTimePicker: false,
				form: {
					logoImage:'',
					storeNumber:'',
					storeName:'',
					investAmount: '',
					mobile: '',
					linkMan: '',
					areaId: '',
					payAccount:'',
					coordinate:'',
					areaFullName:'',
					address:'',
					sharingCode:'',
					openingTime:'',
					closingTime:'',
					isDefault: true,
					isDelete: false,
					staffId: '',
					staffName: ''
				},
				rules: {
					storeName: [{
						required: true,
						message: '门店名称不能为空',
						trigger: ['blur', 'change']
					}],
					linkMan: [{
						required: true,
						message: '联系人不能为空',
						trigger: ['blur', 'change']
					}],
					mobile: [{
						required: true,
						message: '联系电话不能为空',
						trigger: ['blur', 'change']
					}],
					areaId: [{
						required: true,
						message: '门店区域不能为空',
						trigger: ['blur', 'change']
					}],
					address: [{
						required: true,
						message: '门店详细地址不能为空',
						trigger: ['blur', 'change']
					}],
				}
			}
		},
		onLoad(opt) {
			this.type = opt.type
			this.getAreaCheckedList()
			if(opt.id){
				this.getStoreInfo(opt.id)
				uni.setNavigationBarTitle({
					title:'门店资料'
				})
			}
			uni.$on('user-category', obj=>{
				this.form.userCategoryId = obj.id
				this.form.userCategoryName = obj.name
			})
			uni.$on('user-grade', obj=>{
				this.form.gradeId = obj.id
				this.form.gradeName = obj.title
			})
			uni.$on('select-parent', obj => {
				this.form.staffId = obj.id
				this.form.staffName = obj.nickName
			})
		},
		onUnload() {
			uni.$off('user-category')
			uni.$off('user-grade')
			uni.$off('select-parent')
		},
		onReady() {
			this.$refs.myForm.setRules(this.rules)
		},
		methods: {
			viewCode(){
				this.$reqJsonPost('GetStoreQrCode', {id: this.form.id}).then(res=>{
					uni.previewImage({
						urls: [res.data.data]
					})
				})
			},
			onConfirmTime(e){
				if(this.timeType==='open'){
					this.form.openingTime = e.value
				}else {
					this.form.closingTime = e.value
				}
				this.showTimePicker = false
			},
			openTimePick(ty){
				if(this.type==='1'){
					this.showTimePicker = true
					this.timeType = ty
				}
			},
			onSeqy(){
				if(this.type === '1'){
					this.showArea=true
				} 
			},
			async changeHandler(e) {
			  const { columnIndex, value, picker = this.$refs.uAreaPicker } = e;
			  const { id } = value[columnIndex];
	
			  const getAreaChildren = async (id) => {
			    const res = await this.$reqJsonPost('ToolsGetAreaChildren', { id });
			    return [res];
			  };
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
			  if (columnIndex === 0) {
			    const columnData1 = await getAreaChildren(id);
			    picker.setColumnValues(1, columnData1[0]);
					// picker为选择器this实例，变化第二列对应的选项
			    const columnData2 = await getAreaChildren(columnData1[0][0].id);
			    picker.setColumnValues(2, columnData2[0]);
			  } else if (columnIndex === 1) {
			    const columnData3 = await getAreaChildren(id);
			    picker.setColumnValues(2, columnData3[0]);
			  }
			},
			confirmAreas(e){
				this.form.areaId = e.value[2].id
				this.form.areaFullName = e.value[0].name === e.value[1].name?`${e.value[0].name}-${e.value[2].name}`:
				`${e.value[0].name}-${e.value[1].name}-${e.value[2].name}`
				this.showArea = false
			},
			async getAreaCheckedList() {
			  try {
			    const economize = await this.$reqJsonPost('ToolsGetAreaCheckedList', { id: 0 });
			    this.areas[0] = economize[0].list;
			
			    const market = await this.$reqJsonPost('ToolsGetAreaChildren', { id: economize[0].list[0].id });
			    this.areas[1] = market;
			
			    const distinguish = await this.$reqJsonPost('ToolsGetAreaChildren', { id: market[0].id });
			    this.areas[2] = distinguish;
			  } catch (error) {
			    // 处理错误
					console.log('获取地址失败', error)
			  }
			},
			onUserSource(e){
				this.form.sourceText = e.value[0].description
				this.form.source = e.value[0].value
				this.showUserSource = false
			},
			getStoreInfo(id) {
				this.$reqJsonPost('StoreGetEdit',{id:id}).then(res => {
					this.form = res.data
					this.fileList = [{
						url: res.data.logoImage
					}]
				})
			},
			submit() {
				let that = this
				this.$refs.myForm.validate().then(res => {
					that.$reqJsonPost('StoreDoEdit', that.form).then(res=>{
						that.$refs.uToast.show({
							message: res.msg,
							complete() {
								uni.$emit('upStoreList')
								uni.navigateBack()
							}
						})
					})
				})
			},
			getPercent(curNum, totalNum, isHasPercentStr) {
				curNum = parseFloat(curNum);
				totalNum = parseFloat(totalNum);
				if (isNaN(curNum) || isNaN(totalNum)) {
					return '-';
				}
				return isHasPercentStr ?
				totalNum <= 0 ? '0%' : (Math.round(curNum / totalNum * 10000) / 100.00 + '%') :
				totalNum <= 0 ? 0 : (Math.round(curNum / totalNum * 10000) / 100.00);
			},
			// 删除头像
			deletePic(event) {
				this.fileList.splice(event.index, 1)
				this.form.logoImage = ''
			},
			// 新增图片
			async afterRead(event) {
				let lists = [].concat(event.file)
				let fileListLen = this.fileList.length
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.$reqUpLoad(lists[i].url)
					let item = this.fileList[fileListLen]
					this.form.logoImage = result.fileUrl
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.fileUrl
					}))
					fileListLen++
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	
</style>
